<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

/**
 * 快递查询工具API - 修复版
 */
class ExpressToolApi {
    private $db;
    private $token;
    private $apiUrl;
    private $sfPhoneTail;
    
    public function __construct() {
        $this->db = getDB();
        $this->loadConfig();
    }
    
    private function loadConfig() {
        $stmt = $this->db->query("SELECT key_name, key_value FROM settings");
        $settings = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $settings[$row['key_name']] = $row['key_value'];
        }
        
        $this->token = $settings['express_token'] ?? '';
        $this->apiUrl = $settings['express_api_url'] ?? 'https://music.wxnotes.cn/kd';
        $this->sfPhoneTail = $settings['sf_phone_tail'] ?? '';
    }
    
    /**
     * 查询快递信息 - 修复data字段为JSON字符串的问题
     */
    public function queryTracking($trackingNo, $customSfPhoneTail = null) {
        if (empty($this->token)) {
            throw new Exception('请先配置快递查询Token');
        }
        
        if (empty($trackingNo)) {
            throw new Exception('物流单号不能为空');
        }
        
        $url = rtrim($this->apiUrl, '/') . '/query.php';
        
        // 处理顺丰快递单号格式
        $finalTrackingNo = $this->formatTrackingNumber($trackingNo, $customSfPhoneTail);
        
        $data = [
            'token' => $this->token,
            'orderNumber' => $finalTrackingNo
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'User-Agent: OrderSystem/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception('快递查询接口请求失败，HTTP代码: ' . $httpCode . '，错误: ' . $error);
        }
        
        if (empty($response)) {
            throw new Exception('接口返回空响应');
        }
        
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('接口返回数据格式错误: ' . json_last_error_msg());
        }
        
        if (isset($result['error'])) {
            throw new Exception($result['error']);
        }
        
        // 检查物流查询状态
        if (isset($result['data']['status']) && $result['data']['status'] !== '0') {
            $errorMsg = $this->getErrorMessage($result['data']['status']);
            throw new Exception($errorMsg);
        } elseif (isset($result['status']) && $result['status'] !== '0') {
            $errorMsg = $this->getErrorMessage($result['status']);
            throw new Exception($errorMsg);
        }
        
        // 关键修复：处理data字段为JSON字符串的情况
        $parsedData = $this->parseExpressDataFixed($result);
        
        if (!$parsedData) {
            throw new Exception('无法解析物流数据');
        }
        
        return $this->formatResultForFrontend($parsedData, $trackingNo);
    }
    
    /**
     * 修复的解析方法 - 处理data字段为JSON字符串的情况
     */
    private function parseExpressDataFixed($expressData) {
        // 如果data字段是字符串，先解析它
        if (isset($expressData['data']) && is_string($expressData['data'])) {
            $decodedData = json_decode($expressData['data'], true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $expressData['data'] = $decodedData;
            }
        }
        
        // 现在使用标准的解析逻辑
        if (isset($expressData['result'])) {
            return $expressData['result'];
        } elseif (isset($expressData['data']['result'])) {
            return $expressData['data']['result'];
        } elseif (isset($expressData['data']) && is_array($expressData['data'])) {
            return $expressData['data'];
        }
        
        return null;
    }
    
    /**
     * 格式化物流单号
     */
    private function formatTrackingNumber($trackingNo, $customSfPhoneTail = null) {
        // 检查是否为顺丰快递（不区分大小写）
        if (preg_match('/^SF\d+/i', $trackingNo) && !strpos($trackingNo, ':')) {
            $phoneTail = $customSfPhoneTail ?: $this->sfPhoneTail;
            if (!empty($phoneTail) && preg_match('/^\d{4}$/', $phoneTail)) {
                return $trackingNo . ':' . $phoneTail;
            }
        }
        return $trackingNo;
    }
    
    /**
     * 获取错误信息
     */
    private function getErrorMessage($status) {
        $errors = [
            '201' => '快递单号错误',
            '203' => '快递公司不存在',
            '204' => '快递公司识别失败',
            '205' => '没有物流信息',
            '207' => '该单号被限制，错误单号'
        ];
        
        return $errors[$status] ?? '未知错误 (状态码: ' . $status . ')';
    }
    
    /**
     * 格式化结果给前端显示
     */
    private function formatResultForFrontend($parsedData, $trackingNo) {
        $result = [
            'express_company' => $parsedData['expName'] ?? '未知',
            'is_signed' => (isset($parsedData['issign']) && $parsedData['issign'] == '1'),
            'delivery_status' => $parsedData['deliverystatus'] ?? '',
            'update_time' => $parsedData['updateTime'] ?? '',
            'latest_status' => '',
            'latest_time' => '',
            'current_location' => '',
            'transport_time' => $parsedData['takeTime'] ?? '',
            'tracking_list' => []
        ];
        
        // 处理物流轨迹
        if (isset($parsedData['list']) && is_array($parsedData['list'])) {
            $trackingList = [];
            foreach ($parsedData['list'] as $index => $item) {
                $trackingItem = [
                    'time' => $item['time'] ?? '',
                    'status' => $item['status'] ?? '',
                    'location' => '',
                    'is_latest' => $index === 0
                ];
                
                // 从状态信息中提取地点（如果有的话）
                $status = $item['status'] ?? '';
                if (preg_match('/【(.*?)】/', $status, $matches)) {
                    $trackingItem['location'] = $matches[1];
                }
                
                $trackingList[] = $trackingItem;
            }
            
            $result['tracking_list'] = $trackingList;
            
            // 设置最新状态
            if (!empty($trackingList)) {
                $latest = $trackingList[0];
                $result['latest_status'] = $latest['status'] ?? '';
                $result['latest_time'] = $latest['time'] ?? '';
                $result['current_location'] = $latest['location'] ?? '';
                
                // 如果API没有提供takeTime，计算运输时长
                if (empty($result['transport_time'])) {
                    $result['transport_time'] = $this->calculateTransportTime($trackingList);
                }
            }
        } else {
            // 如果没有轨迹信息，使用默认状态
            $result['latest_status'] = $parsedData['message'] ?? '暂无物流信息';
        }
        
        return $result;
    }
    
    /**
     * 计算运输时长
     */
    private function calculateTransportTime($trackingList) {
        if (empty($trackingList)) {
            return '-';
        }
        
        $firstTime = null;
        $lastTime = null;
        
        foreach ($trackingList as $item) {
            $timeStr = $item['time'] ?? '';
            if (!empty($timeStr)) {
                $time = strtotime($timeStr);
                if ($time) {
                    if ($firstTime === null || $time < $firstTime) {
                        $firstTime = $time;
                    }
                    if ($lastTime === null || $time > $lastTime) {
                        $lastTime = $time;
                    }
                }
            }
        }
        
        if ($firstTime && $lastTime) {
            $diff = $lastTime - $firstTime;
            $days = floor($diff / (60 * 60 * 24));
            $hours = floor(($diff % (60 * 60 * 24)) / (60 * 60));
            
            if ($days > 0) {
                return $days . '天' . $hours . '小时';
            } elseif ($hours > 0) {
                return $hours . '小时';
            } else {
                $minutes = floor($diff / 60);
                return $minutes > 0 ? $minutes . '分钟' : '刚刚';
            }
        }
        
        return '-';
    }
    
    /**
     * 批量查询快递信息
     */
    public function batchQueryTracking($trackingNumbers, $customSfPhoneTail = null) {
        if (empty($this->token)) {
            throw new Exception('请先配置快递查询Token');
        }
        
        if (empty($trackingNumbers) || !is_array($trackingNumbers)) {
            throw new Exception('物流单号列表不能为空');
        }
        
        $results = [];
        $successCount = 0;
        
        foreach ($trackingNumbers as $index => $trackingNo) {
            try {
                $result = $this->queryTracking($trackingNo, $customSfPhoneTail);
                $results[] = [
                    'trackingNo' => $trackingNo,
                    'success' => true,
                    'data' => $result
                ];
                $successCount++;
                
                // 添加延迟避免请求过于频繁
                if ($index < count($trackingNumbers) - 1) {
                    usleep(500000); // 500ms延迟
                }
                
            } catch (Exception $e) {
                $results[] = [
                    'trackingNo' => $trackingNo,
                    'success' => false,
                    'message' => $e->getMessage()
                ];
            }
        }
        
        return [
            'results' => $results,
            'total' => count($trackingNumbers),
            'success' => $successCount,
            'failed' => count($trackingNumbers) - $successCount
        ];
    }
    
    /**
     * 导入物流单号文件
     */
    public function importTrackingNumbers($file) {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('文件上传失败');
        }
        
        $trackingNumbers = [];
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        // 检查文件类型
        $allowedTypes = ['text/plain', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];
        
        if (!in_array($file['type'], $allowedTypes) && !in_array($fileExtension, ['txt', 'csv', 'xls', 'xlsx'])) {
            throw new Exception('不支持的文件类型，请上传 TXT、CSV 或 Excel 文件');
        }
        
        try {
            if ($fileExtension == 'txt' || $fileExtension == 'csv') {
                // 处理文本文件
                $content = file_get_contents($file['tmp_name']);
                $lines = explode("\n", $content);
                
                foreach ($lines as $line) {
                    $line = trim($line);
                    if (!empty($line)) {
                        $trackingNumbers[] = $line;
                    }
                }
            } elseif (in_array($fileExtension, ['xls', 'xlsx'])) {
                // 处理Excel文件
                require_once __DIR__ . '/../../vendor/autoload.php';
                
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
                $worksheet = $spreadsheet->getActiveSheet();
                
                foreach ($worksheet->getRowIterator() as $row) {
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false);
                    
                    foreach ($cellIterator as $cell) {
                        $value = trim($cell->getValue());
                        if (!empty($value)) {
                            $trackingNumbers[] = $value;
                            break; // 只取每行第一列
                        }
                    }
                }
            }
            
            if (empty($trackingNumbers)) {
                throw new Exception('文件中没有找到有效的物流单号');
            }
            
            // 去重
            $trackingNumbers = array_unique($trackingNumbers);
            $trackingNumbers = array_values($trackingNumbers);
            
            return $trackingNumbers;
            
        } catch (Exception $e) {
            throw new Exception('文件处理失败：' . $e->getMessage());
        }
    }
}

// API 路由处理
$action = $_POST['action'] ?? '';

try {
    $api = new ExpressToolApi();
    
    switch ($action) {
        case 'query_tool':
            $trackingNo = $_POST['tracking_no'] ?? '';
            $sfPhoneTail = $_POST['sf_phone_tail'] ?? null;
            
            if (empty($trackingNo)) {
                throw new Exception('物流单号不能为空');
            }
            
            $result = $api->queryTracking($trackingNo, $sfPhoneTail);
            
            echo json_encode([
                'success' => true,
                'data' => $result,
                'message' => '查询成功'
            ]);
            break;
            
        case 'batch_query_tool':
            $trackingNumbersJson = $_POST['tracking_numbers'] ?? '[]';
            $sfPhoneTail = $_POST['sf_phone_tail'] ?? null;
            
            $trackingNumbers = json_decode($trackingNumbersJson, true);
            if (!is_array($trackingNumbers) || empty($trackingNumbers)) {
                throw new Exception('物流单号列表不能为空');
            }
            
            // 限制批量查询数量，避免超时
            $maxBatchSize = 50;
            if (count($trackingNumbers) > $maxBatchSize) {
                $trackingNumbers = array_slice($trackingNumbers, 0, $maxBatchSize);
            }
            
            $result = $api->batchQueryTracking($trackingNumbers, $sfPhoneTail);
            
            echo json_encode([
                'success' => true,
                'data' => $result,
                'message' => '批量查询完成'
            ]);
            break;
            
        case 'import_tracking_numbers':
            if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('请选择要上传的文件');
            }
            
            $file = $_FILES['file'];
            $trackingNumbers = $api->importTrackingNumbers($file);
            
            echo json_encode([
                'success' => true,
                'data' => $trackingNumbers,
                'message' => '导入成功，共找到 ' . count($trackingNumbers) . ' 个物流单号'
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => '未知操作'
            ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>